<template>
    <div class="prepare-add i_maxW">
        <div class="prepare-crumbs">
            <span @click="goBack">备课 </span>
            <span><i>></i>新建</span>
        </div>
        <div class="prepare-add-cont" v-loading="loading4" element-loading-text="上传文件中...">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="备课类型" prop="type">
                    <el-radio-group v-model="ruleForm.type">
                        <el-radio :label="0">个人备课</el-radio>
                        <el-radio :label="1">集体备课</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备课名称" prop="name">
                    <el-input v-model="ruleForm.name" maxlength="30" placeholder="请输入备课名称"></el-input>
                </el-form-item>
                <el-form-item label="备课目标" prop="target" class="prepare-target">
                    <el-input type="textarea" :rows="4" resize="none" v-model="ruleForm.target" maxlength="200" placeholder="请输入备课目标"></el-input>
                    <span><i>{{ruleForm.target.length}}</i>/200</span>
                </el-form-item>
                <el-form-item label="截止日期" prop="date" class="prepare-date" v-if="ruleForm.type == 1">
                    <!--    <el-date-picker type="datetime"  placeholder="选择日期"  v-model="ruleForm.date" value-format="yyyy-MM-dd HH:mm" :picker-options="pickerOptionsStart"></el-date-picker> -->
                    <el-date-picker v-model="ruleForm.date" type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm" :picker-options="pickerOptionsStart">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label-width="46px" class="prepare-add-select">
                    <!-- 学段-年级-科目 -->
                    <selection ref="selection" required></selection>
                </el-form-item>
                <template v-if="ruleForm.type == 1">
                    <el-form-item label="邀请老师" prop="teachArr" class="prepare-invitation">
                        <el-button type="primary" @click="inviteTeacher">选择</el-button>
                        <div>
                            <el-tag v-for="(tag, index) in teachlistID" :key="index" closable @close="handleClose(index,tag.id)">
                                {{tag.name}}
                            </el-tag>
                        </div>
                        <el-checkbox-group v-model="ruleForm.teachArr">
                            <el-checkbox v-for="(item, index)  of teachlistID" :label="item.id" name="type" :key="index"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </template>
                <template>
                    <el-form-item label="上传教案" class="prepare-add-upBtn">
                        <el-button type="primary" plain @click="videoShow()">关联视频</el-button>
                        <el-button type="primary" plain @click="testShow()">关联试卷</el-button>
                        <el-button type="primary" plain @click="resourceShow()">关联资源</el-button>
                        <uploader :options="uploadOptions" :autoStart="true" ref="uploaderRes" :file-status-text="statusText" @file-added="fileAddRes" @file-success="fileSuccessRes" @file-error="fileFailRes" class="uploader-add-album">
                            <uploader-unsupport></uploader-unsupport>
                            <uploader-btn :directory="false" :single="true">本地上传</uploader-btn>
                            <!-- <uploader-list></uploader-list> -->
                        </uploader>
                    </el-form-item>
                    <div class="prepare-relation">
                        <h3>视频</h3>
                        <ul>
                            <li class="prepare-relation-list clear" v-for="(item, index) of ruleForm.videoArr" :key="item.id">
                                <span class="fl">{{item.name}}</span>
                                <i class="el-icon-close fr" @click="removeVideo(index,item.id)"></i>
                            </li>
                        </ul>
                    </div>
                    <div class="prepare-relation">
                        <h3>试卷</h3>
                        <ul>
                            <li class="prepare-relation-list clear" v-for="(item, index) of ruleForm.testArr" :key="item.id">
                                <span class="fl">{{item.name}}</span>
                                <i class="el-icon-close fr" @click="removeTest(index,item.id)"></i>
                            </li>
                        </ul>
                    </div>
                    <div class="prepare-relation">
                        <h3>资源</h3>
                        <ul>
                            <li class="prepare-relation-list clear" v-for="(item, index) of ruleForm.resourceArr" :key="item.id">
                                <span class="fl">{{item.name}}</span>
                                <i class="el-icon-close fr" @click="removeResource(index,item.id)"></i>
                            </li>
                        </ul>
                    </div>
                </template>
                <el-form-item class="prepare-submit buttonCSS" label-width="0">
                    <el-button @click="resetForm('ruleForm')" plain>取消</el-button>
                    <el-button type="primary" v-preventReClick="1000" @click="submitForm('ruleForm')">保存</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 选择教师 -->
        <el-dialog title="选择教师" :visible.sync="teachVisible" width="800px" top="10vh" custom-class="relation-dialog" :close-on-click-modal="false">
            <div class="relation-cont">
                <div class="relation-op" v-if="0">
                    <el-input placeholder="请输入视频名称" suffix-icon="el-icon-search" v-model="teachKeyword">
                    </el-input>
                </div>
                <!--  -->
                <div class="relation-batle" v-loading="loading4" element-loading-text="拼命加载中">
                    <template>
                        <el-table ref="teacherTable" :data="teachList" :border="true" tooltip-effect="dark" style="width: 100%"
                         @selection-change="teachSelectionChange" :row-key="getRowKeys" :row-class-name="teachRowClassName">
                            <el-table-column type="selection" width="40" :reserve-selection="true" :selectable="checkTeach">
                            </el-table-column>
                            <el-table-column prop="number" label="登录账户" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="name" label="用户名" width="120" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="sub_name" label="科目" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="rename" label="组织架构" show-overflow-tooltip>
                            </el-table-column>
                        </el-table>
                    </template>
                    <el-pagination @size-change="teachChangeSize" @current-change="teachChange" :current-page.sync="page_index4" :page-size="page_size4" layout="sizes,total, prev, pager, next" :page-sizes="[10, 20, 30, 50, 100]" :total="total_sum4">
                    </el-pagination>
                </div>
                <div class="relation-btn buttonCSS">
                    <el-button type="primary" @click="teachVisible = false" plain>取消</el-button>
                    <el-button type="primary" @click="teachSbulmit()">确定</el-button>
                    <!-- <el-button type="primary" @click="toggleSelection(teachList2)">确定2</el-button> -->
                </div>
            </div>
        </el-dialog>
        <!-- 选择视频 -->
        <el-dialog title="选择视频" :visible.sync="videoVisible" width="800px" top="10vh" custom-class="relation-dialog" :close-on-click-modal="false">
            <div class="relation-cont">
                <div class="relation-op">
                    <el-select v-model="videoType" placeholder="请选择" @change="changeVideoList">
                        <el-option label="全部" :value="-1"> </el-option>
                        <el-option label="公开课" :value="0"> </el-option>
                    </el-select>
                    <el-input placeholder="请输入视频名称" suffix-icon="el-icon-search" @change="changeVideoList" v-model="videoKeyword">
                    </el-input>
                </div>
                <div class="relation-batle" v-loading="loading" element-loading-text="拼命加载中">
                    <template>
                        <el-table ref="videoTable" :data="videoList" :border="true" tooltip-effect="dark" style="width: 100%" 
                        @selection-change="videoSelectionChange" :row-key="getRowKeys" :row-class-name="videoRowClassName">
                            <el-table-column type="selection" width="40" :reserve-selection="true" :selectable="checkVideo">
                            </el-table-column>
                            <el-table-column prop="video_name" label="视频名称" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="category" label="视频分类" show-overflow-tooltip>
                            </el-table-column>
                            <!--    <el-table-column
                          prop="profile"
                          label="视频信息"
                          show-overflow-tooltip>
                        </el-table-column> -->
                            <el-table-column prop="create_time" label="上传时间" show-overflow-tooltip>
                            </el-table-column>
                        </el-table>
                    </template>
                    <el-pagination @size-change="videoChangeSize" @current-change="videoChange" :current-page.sync="page_index" :page-size="page_size" layout="sizes, total, prev, pager, next" :page-sizes="[10, 20, 30, 50, 100]" :total="total_sum">
                    </el-pagination>
                </div>
                <div class="relation-btn buttonCSS">
                    <el-button type="primary" @click="videoVisible = false" plain>取消</el-button>
                    <el-button type="primary" @click="vodeoSbulmit()">确定</el-button>
                </div>
            </div>
        </el-dialog>
        <!-- 选择试卷 -->
        <el-dialog title="选择试卷" :visible.sync="testVisible" width="800px" top="10vh" custom-class="relation-dialog" :close-on-click-modal="false">
            <div class="relation-cont">
                <div class="relation-op">
                    <el-select v-model="testType" placeholder="请选择" @change="changegTestList" v-if='0'>
                        <el-option label="全部" :value="-1"> </el-option>
                        <el-option label="公开" :value="1"> </el-option>
                        <el-option label="私人" :value="0"> </el-option>
                    </el-select>
                    <el-input placeholder="请输入试卷名称" suffix-icon="el-icon-search" @change="changegTestList" v-model="testKeyword">
                    </el-input>
                </div>
                <!--  -->
                <div class="relation-batle" v-loading="loading2" element-loading-text="拼命加载中">
                    <template>
                        <el-table ref="testTable" :data="testList" :border="true" tooltip-effect="dark" style="width: 100%" @selection-change="testSelectionChange" :row-key="getRowKeys" :row-class-name="testRowClassName">
                            <el-table-column type="selection" width="40" :reserve-selection="true" :selectable="checkTest">
                            </el-table-column>
                            <el-table-column prop="name" label="试卷名称" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="grade" label="试卷分类" show-overflow-tooltip>
                            </el-table-column>
                            <!--      <el-table-column
                          prop="_authority"
                          label="试卷信息"
                          show-overflow-tooltip>
                        </el-table-column> -->
                            <el-table-column prop="create_time" label="组卷时间" show-overflow-tooltip>
                            </el-table-column>
                        </el-table>
                    </template>
                    <el-pagination @size-change="testChangeSize" @current-change="testChange" :current-page.sync="page_index2" :page-size="page_size2" layout="sizes, total, prev, pager, next" :page-sizes="[10, 20, 30, 50, 100]" :total="total_sum2">
                    </el-pagination>
                </div>
                <div class="relation-btn buttonCSS">
                    <el-button type="primary" @click="testVisible = false" plain>取消</el-button>
                    <el-button type="primary" @click="testSbulmit()">确定</el-button>
                </div>
            </div>
        </el-dialog>
        <!-- 选择资源 -->
        <el-dialog title="选择资源" :visible.sync="resourceVisible" width="800px" top="10vh" custom-class="relation-dialog" :close-on-click-modal="false">
            <div class="relation-cont">
                <div class="relation-op">
                    <el-select v-model="resourceType" placeholder="请选择" @change="changeResourceList" v-if='0'>
                        <el-option label="全部" :value="-1"> </el-option>
                        <el-option label="公开资源" :value="1"> </el-option>
                        <el-option label="私人资源" :value="0"> </el-option>
                    </el-select>
                    <el-input placeholder="请输入资源名称" suffix-icon="el-icon-search" @change="changeResourceList" v-model="resourceKeyword">
                    </el-input>
                </div>
                <!--  -->
                <div class="relation-batle" v-loading="loading3" element-loading-text="拼命加载中">
                    <template>
                        <el-table ref="resourceTable" :data="resourceList" :border="true" tooltip-effect="dark" style="width: 100%" @selection-change="resourceSelectionChange" :row-key="getRowKeys" :row-class-name="resourceRowClassName">
                            <el-table-column type="selection" width="40" :reserve-selection="true" :selectable="checkResource">
                            </el-table-column>
                            <el-table-column prop="name" label="资源名称" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="category" label="资源分类" show-overflow-tooltip>
                            </el-table-column>
                            <!--        <el-table-column
                          prop="picture"
                          label="资源信息"
                          show-overflow-tooltip>
                        </el-table-column> -->
                            <el-table-column prop="create_time" label="创建时间" show-overflow-tooltip>
                            </el-table-column>
                        </el-table>
                    </template>
                    <el-pagination @size-change="resourceChangeSize" @current-change="resourceChange" :current-page.sync="page_index3" :page-size="page_size3" layout="sizes,total, prev, pager, next" :page-sizes="[10, 20, 30, 50, 100]" :total="total_sum3">
                    </el-pagination>
                </div>
                <div class="relation-btn buttonCSS">
                    <el-button type="primary" @click="resourceVisible = false" plain>取消</el-button>
                    <el-button type="primary" @click="resourceSbulmit()">确定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import selection from './prepare-add-select';
export default {
    components: {
        selection
    },
    data() {
        return {
            pickerOptionsStart: {
                disabledDate: (time) => {
                    return time.getTime() < parseInt(Date.now() - 8.64e7);
                },
                // selectableRange: '18:30:00 - 20:30:00'
            },
            ruleForm: {
                type: +this.$route.query.type,
                name: '',
                target: '',
                date: new Date(),
                teachArr: [],
                videoArr: [],
                testArr: [],
                resourceArr: [],
                teachList: []
            },
            rules: {
                type: [
                    { required: true, message: '请选择活动资源', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入备课名称', trigger: 'blur' },
                ],
                target: [
                    { required: true, message: '请输入备课目标', trigger: 'blur' }
                ],
                date: [
                    // {  required: true, message: '请选择日期', trigger: 'change' },
                    { type: 'date', required: true, validator: this.validateDateTime, trigger: "change" }
                ],
                teachArr: [
                    { required: true, message: '请选择邀请老师', trigger: 'change' }
                ]
            },

            teachVisible: false,
            teachKeyword: '',
            teachlection: [],
            teachList: [],
            page_index4: 1,
            page_size4: this.$g.page_size,
            total_sum4: 0,
            loading4: true,

            videoVisible: false,
            videoType: -1,
            videoKeyword: '',
            videoSelection: [],
            videoList: [],
            page_index: 1,
            page_size: this.$g.page_size,
            total_sum: 0,
            loading: true,

            testVisible: false,
            testType: -1,
            testKeyword: '',
            testSelection: [],
            testList: [],
            page_index2: 1,
            page_size2: this.$g.page_size,
            total_sum2: 0,
            loading2: true,

            resourceVisible: false,
            resourceType: 0,
            resourceKeyword: '',
            resourcelection: [],
            resourceList: [],
            resourceType: -1,
            page_index3: 1,
            page_size3: this.$g.page_size,
            total_sum3: 0,
            loading3: true,

            statusText: {
                success: '上传成功',
                error: '上传出错',
                uploading: '正在上传...',
                paused: '暂停',
                waiting: '等待上传'
            },
            selectFileOrNot: false, //是否选中文件
            uploadInfo: {
                file_name: '',
                file_path: '',
                file_size: 0
            },
            attrs: {
                accept: ['image/*']
            },

            uploadOptions: {
                target: this.BASE_URL + '/api/resource/res_upload',
                testChunks: false,
                headers: { Authorization: `Bearer ` + this.$g.access_token },
            },
            selectFileShow: true, //是否显示选择文件按钮
            uploadRetryTimes: 100, //文件最大重传次数
            previewImgURL: '',
            fileNumber: 0,
            uploadNumber: 0,
            loading4: false,
            teachlistID: [],
            teachArr: [],
        };
    },
    created() {},
    watch: {
        'ruleForm.type'(a, b) {
            if (a === 0) {
                this.teachlistID = []
                this.ruleForm.teachArr = []
                this.ruleForm.date = ''
            }
        }
    },
    methods: {
        /**
         * 选择的资源高亮
         * @DateTime 2020-06-03T15:53:56+0800
         * @qiu_m
         * @param    {[type]}                 row [description]
         * @return   {[type]}                     [description]
         */
        checkResource(row) {
            return this.setArr(this.ruleForm.resourceArr).includes(row.id) ? false : true
        },
        resourceRowClassName({ row, rowIndex }) {
            return this.setArr(this.ruleForm.resourceArr).includes(row.id) ? 'warning-row' : '';
        },
        /**
         * 选择的试卷高亮
         * @DateTime 2020-06-03T15:53:56+0800
         * @qiu_m
         * @param    {[type]}                 row [description]
         * @return   {[type]}                     [description]
         */
        checkTest(row) {
            return this.setArr(this.ruleForm.testArr).includes(row.id) ? false : true
        },
        testRowClassName({ row, rowIndex }) {
            return this.setArr(this.ruleForm.testArr).includes(row.id) ? 'warning-row' : '';
        },
        /**
         * 选择的视频高亮
         * @DateTime 2020-06-03T15:53:56+0800
         * @qiu_m
         * @param    {[type]}                 row [description]
         * @return   {[type]}                     [description]
         */
        checkVideo(row) {
            return this.setArr(this.ruleForm.videoArr).includes(row.id) ? false : true
        },
        videoRowClassName({ row, rowIndex }) {
            return this.setArr(this.ruleForm.videoArr).includes(row.id) ? 'warning-row' : '';
        },
        /**
         * 选择的教室高亮
         * @DateTime 2020-06-03T15:53:56+0800
         * @qiu_m
         * @param    {[type]}                 row [description]
         * @return   {[type]}                     [description]
         */
        checkTeach(row) {
            return !this.ruleForm.teachArr.includes(row.id)
        },
        teachRowClassName({ row, rowIndex }) {
            return this.ruleForm.teachArr.includes(row.id) ? 'warning-row' : '';
        },
        /**
         * row里面有id作为唯一标识
         */
        getRowKeys(row) {
            return row.id;
        },
        /**
         * [setArr description]
         * @DateTime 2020-06-02T17:20:37+0800
         * @qiu_m
         * @param    {[type]}                 arr    [description]
         * @param    {[type]}                 newArr [description]
         */
        setArr(arr, newArr) {

            newArr = newArr || [];
            arr.length > 0 && arr.forEach(item => {
                (item.id || item.id == 0) && newArr.push(item.id);
                item.relate_data && this.setArr(item.relate_data, newArr);
            })
            return newArr;
        },

        goBack() {
            this.$router.back(-1)
        },
        inviteTeacher() {
            this.teachVisible = true;
            this.getTeacher()
        },

        getTeacher() {
            let success = (res => {
                this.loading4 = false;
                this.teachList = res.data.data;
                this.total_sum4 = parseInt(res.data.data_sum);
            })
            if (this.$store.getters.isMulti && !this.$store.getters.isSchool) {
                this.$ajax({
                    url: 'api/prepare/get_teacher_list',
                    method: 'get',
                    params: {
                        page: this.page_index4,
                        size: this.page_size4,
                        app_code: sessionStorage.getItem('CheckSchollAppCode')
                    },
                    func: { success: success }
                })
            } else {
                this.$ajax({
                    url: 'api/user/user',
                    method: 'get',
                    params: {
                        page: this.page_index4,
                        size: this.page_size4,
                        role_id: 6,
                        data_type: 2,
                        status: 1
                    },
                    func: { success: success }
                })

            }

        },
        // 选择教师
        teachSbulmit() {
            if (this.teachlection.length === 0) {
                this.$message.error('请勾选');
                return
            }
            this.ruleForm.teachArr = [];
            for (let i = 0; i < this.teachlection.length; i++) {
                this.teachlistID.push(this.teachlection[i])

                if (this.teachlection[i].id) {
                    this.ruleForm.teachArr.push(this.teachlection[i].id)
                }
            }

            /*去重 */
            let hash = {};
            let arr = this.teachlistID.reduceRight((item, next) => {
                hash[next.id] ? '' : hash[next.id] = true && item.push(next);
                return item
            }, [])

            this.teachlistID = arr

            this.teachVisible = false
        },

        handleClose(index,teacherId) {
            this.teachlection.splice(this.teachlection.findIndex(x => x.id === teacherId), 1);
            this.$refs.teacherTable.selection.splice(this.$refs.teacherTable.selection.findIndex(x => x.id === teacherId), 1);
            this.teachlistID.splice(index, 1);
            this.ruleForm.teachArr.splice(this.ruleForm.teachArr.findIndex(x => x === teacherId), 1);
        },
        teachChange(val) {
            this.page_index4 = val;
            this.getTeacher()
        },
        teachChangeSize(val) {
            this.page_index4 = 1;
            this.page_size4 = val;
            this.getTeacher()
        },
        teachSelectionChange(val) {
            this.teachlection = val;
        },
        // 视频
        videoShow() {
            this.videoVisible = true;
            this.getVideoList()
        },
        changeVideoList() {
            this.page_index = 1
            this.getVideoList()
        },
        getVideoList() {
            let success = (res => {
                this.videoList = res.data.data;
                this.total_sum = parseInt(res.data.data_sum)
                this.loading = false;

                // this.videoList.forEach(item=>{
                //     console.log(item);
                //     this.$refs.videoTable.toggleRowSelection(item, true);

                // })
                // this.$forceUpdate()

            })

            this.$ajax({
                url: 'api/video/video_list',
                method: 'get',
                params: {
                    page_index: this.page_index,
                    page_size: this.page_size,
                    status: 1,
                    authority: 1,
                    video_name: this.videoKeyword,
                    type: this.videoType,
                    check_app_code: sessionStorage.getItem('CheckSchoolAppCode'),
                    // create_id: this.$g.user_id,
                    // other_authority: 1,
                },
                func: { success: success }
            })
        },
        removeVideo(index,videoId) {
            this.videoSelection.splice(this.videoSelection.findIndex(x => x.id === videoId), 1);
            this.$refs.videoTable.selection.splice(this.$refs.videoTable.selection.findIndex(x => x.id === videoId), 1);
            this.ruleForm.videoArr.splice(this.ruleForm.videoArr.findIndex(x => x.id === videoId), 1);
        },
        // 选择视频
        vodeoSbulmit() {
            if (this.videoSelection.length === 0) {
                this.$message.error('请勾选');
                return
            }

            for (let i = 0; i < this.videoSelection.length; i++) {
                this.ruleForm.videoArr.push({
                    name: this.videoSelection[i].video_name,
                    id: this.videoSelection[i].id,
                    origin: 0
                })
            }
            /*去重 */
            let hash = {};
            let arr = this.ruleForm.videoArr.reduceRight((item, next) => {
                hash[next.id] ? '' : hash[next.id] = true && item.push(next);
                return item
            }, [])

            this.ruleForm.videoArr = arr

            this.videoVisible = false;
        },
        videoChange(val) {
            this.page_index = val;
            this.getVideoList()
        },
        videoChangeSize(val) {
            this.page_index = 1;
            this.page_size = val;
            this.getVideoList()
        },
        videoSelectionChange(val) {
            this.videoSelection = val;
        },
        // 试卷
        testShow() {
            this.testVisible = true
            this.getTestList()
        },
        changegTestList(){
            this.page_index2 = 1
            this.getTestList()
        },
        getTestList() {
            let success = (res => {
                this.testList = res.data.data;
                this.total_sum2 = parseInt(res.data.data_sum)
                this.loading2 = false
            });

            this.$ajax({
                url: 'api/newtest/test_list',
                method: 'get',
                params: {
                    keyword: this.testKeyword,
                    page_index: this.page_index2,
                    page_size: this.page_size2,
                    status: 1,
                    authority: 1,
                    check_app_code:sessionStorage.getItem('CheckSchoolAppCode')
                    // status: '1,2,3',
                    // user_id: this.$g.user_id,
                    // other_authority:this.testType,
                    // authority: this.testType

                },
                func: { success: success }
            })
        },
        testSbulmit() {
            if (this.testSelection.length === 0) {
                this.$message.error('请勾选');
                return
            }
            for (let i = 0; i < this.testSelection.length; i++) {
                this.ruleForm.testArr.push({
                    name: this.testSelection[i].name,
                    id: this.testSelection[i].id,
                    origin: 1
                })
            }
            /*去重 */
            let hash = {};
            let arr = this.ruleForm.testArr.reduceRight((item, next) => {
                hash[next.id] ? '' : hash[next.id] = true && item.push(next);
                return item
            }, [])
            this.ruleForm.testArr = arr

            this.testVisible = false;
        },
        removeTest(index,testId) {
            this.$refs.testTable.selection.splice(this.$refs.testTable.selection.findIndex(x => x.id === testId), 1);
            this.testSelection.splice(this.testSelection.findIndex(x => x.id === testId), 1);
            this.ruleForm.testArr.splice(this.ruleForm.testArr.findIndex(x => x.id === testId), 1);
        },
        testChange(val) {
            this.page_index2 = val;
            this.getTestList()
        },
        testChangeSize(val) {
            this.page_index2 = 1;
            this.page_size2 = val;
            this.getTestList()
        },
        testSelectionChange(val) {
            this.testSelection = val;
        },
        // 资源
        resourceShow() {
            this.resourceVisible = true;
            this.getResourceList()
        },
        changeResourceList(){
            this.page_index3 = 1
            this.getResourceList()
        },
        getResourceList() {
            let success = (res => {
                this.resourceList = res.data.data;
                this.total_sum3 = parseInt(res.data.data_sum)
                this.loading3 = false;

            });

            let params = '';
            // 全部 -1, 公开 1, 私人 0

            if (this.resourceType == -1) {
                params = {

                    resource_name: this.resourceKeyword,
                    page: this.page_index3,
                    size: this.page_size3,
                    data_type: 2,
                    // status: 1,
                    // authonity: 0,
                    // create_id: this.$g.user_id,
                    // other_authority: 1,
                    check_app_code: sessionStorage.getItem('CheckSchoolAppCode'),
                    status: 1,
                    authonity: 1,
                }
            } else if (this.resourceType == 1) {
                params = {
                    page: this.page_index3,
                    size: this.page_size3,
                    resource_name: this.resourceKeyword,
                    data_type: 2,
                    status: 1,
                    authonity: 1,
                    check_app_code: sessionStorage.getItem('CheckSchoolAppCode')
                }
            } else if (this.resourceType == 0) {
                params = {
                    page: this.page_index3,
                    size: this.page_size3,
                    resource_name: this.resourceKeyword,
                    data_type: 2,
                    // status: 1,
                    // authonity: 0,
                    // create_id: this.$g.user_id,
                    check_app_code: sessionStorage.getItem('CheckSchoolAppCode'),
                    status: 1,
                    authonity: 1,
                }
            }

            this.$ajax.get('api/resource/resource', { params, func: { success: success } })
        },

        resourceSbulmit() {
            if (this.resourceSelection.length === 0) {
                this.$message.error('请勾选');
                return
            }


            for (let i = 0; i < this.resourceSelection.length; i++) {
                this.ruleForm.resourceArr.push({
                    name: this.resourceSelection[i].name,
                    id: this.resourceSelection[i].id,
                    origin: 2,
                })
            }
            /*去重 */
            let hash = {};
            let arr = this.ruleForm.resourceArr.reduceRight((item, next) => {
                hash[next.id] ? '' : hash[next.id] = true && item.push(next);
                return item
            }, [])

            this.ruleForm.resourceArr = arr

            this.resourceVisible = false;
        },
        fileAddRes(file) { /*本地文件上传 */
            if (file.size > 2000 * 1024 * 1024) {
                this.$message.error("附件大小不能超过2G");
                file.ignored = true;
                return false;
            }
            this.loading4 = true;
        },
        //上传成功的事件  
        fileSuccessRes(rootFile, file, message, chunk) {
            this.$refs.uploaderRes.uploader.cancel();
            this.loading4 = false;

            let mess = eval('(' + message + ')');
            mess = handleResponseData(mess);

            this.ruleForm.resourceArr.push({
                origin: 2,
                name: mess.data.file_name,
                file_path: mess.data.file_path,
                post_fix: mess.data.post_fix,
                name_up: mess.data.file_name
            })
        },
        fileFailRes(rootFile, file, message, chunk) {
            var mess = eval('(' + message + ')');
            if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
                let callbcak = (data => {
                    this.uploadRetryTimes--;
                    this.$refs.uploaderRes.uploader.retry(file);
                })
                this.get_access_token(callbcak);
            } else {
                this.$message.error(mess.data.msg);
            }
        },
        removeResource(index,resId) {
            this.$refs.resourceTable.selection.splice(this.$refs.resourceTable.selection.findIndex(x => x.id === resId), 1);
            this.resourceSelection.splice(this.resourceSelection.findIndex(x => x.id === resId), 1);
            this.ruleForm.resourceArr.splice(this.ruleForm.resourceArr.findIndex(x => x.id === resId), 1);
        },
        resourceChange(val) {
            this.page_index3 = val;
            this.getResourceList()
        },
        resourceChangeSize(val) {
            this.page_index3 = 1;
            this.page_size3 = val;
            this.getResourceList()
        },
        resourceSelectionChange(val) {
            this.resourceSelection = val;
        },
        submitForm(formName) {

            let arr = this.ruleForm.videoArr
            let arr2 = arr.concat(this.ruleForm.testArr)
            let arr3 = arr2.concat(this.ruleForm.resourceArr)

            let arr4 = []
            for (let i = 0; i < arr3.length; i++) {
                arr4.push(`${arr3[i].id || arr3[i].file_path},${arr3[i].origin},${arr3[i].name_up === 'undefined' ? '' : arr3[i].name_up}`)
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 验证学段-年级-科目的值
                    this.$refs.selection.valid();
                    const flag = Object.values(this.$refs.selection.ruleForm).includes('');
                    if (flag) return;

                    // let timestampToTime = deep_clone(this.ruleForm.date)
                    let success = (res => {
                        this.$message.success(res.msg);

                        if (this.ruleForm.type === 0) {
                            this.$router.push({ path: '/prepare' })
                        } else {
                            this.$router.push({ path: '/prepare/collective' })
                        }
                    });

                    let params = {
                        type: this.ruleForm.type,
                        preparename: this.ruleForm.name,
                        profile: this.ruleForm.target,

                        study_section_id: this.$refs.selection.ruleForm.section,
                        grade_id: this.$refs.selection.ruleForm.grade,
                        subject: this.$refs.selection.ruleForm.subject,

                        create_id: this.$g.user_id,
                        end_time: this.ruleForm.date,
                        teacherid: this.ruleForm.teachArr,
                        videoid: arr4
                    }

                    this.$ajax.post('api/prepare/prepare', params, { func: { success: success } })

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            //  this.$refs.selection.reset();
            // this.$refs[formName].resetFields();
            this.$router.back(-1) // 
        },
        // 验证截至时间是否小于当前时间
        validateDateTime(rule, value, callback) {
            if (value === '') {
                return callback(new Error('截至时间不能为空'));
            } else if (new Date(this.ruleForm.date).getTime() < new Date().getTime()) {
                return callback(new Error('截至时间不能小于当前时间'));
            } else {
                callback()
            }
        },
    }
}
</script>